package cn.cinz.cyxx.util;

import cn.cinz.cyxx.common.enums.ESendSms;
import cn.cinz.cyxx.model.Code;
import redis.clients.jedis.Jedis;

/**
* Redis 校验 短信验证码 Util类
* @ClassName RedisVerifyPhoneCodeUtils
* @Description Redis 校验 短信验证码 Util类
* @Author zengcheng
* @Date 2021/10/2 20:43
* @Version 1.0
*/
public class RedisVerifyPhoneCodeUtils {

    /**
     * 每个手机只能发送三次，验证码放到redis中，设置过期时间为300s
     * 存放发送次数
     * @param phone 手机号
     * @return
     */
    public static String getVerifyCode(String phone){

        String verifyCodeMsg = "";
        Jedis jedis = RedisUtil.getRedis("192.168.10.2");
        try {
            //手机发送次数key
            String countKey = "PhoneNumbers:"+phone+",count:";
            //验证码key
            String codeKey = "PhoneNumbers:"+phone+",code:";

            //每个手机号一个小时发送次数不能超过三次  （待实现：一分钟只能发送一次）
            String count = jedis.get(countKey);
            if (count == null){
                //没有发送，第一次发送
                //设置发送次数为1
                jedis.setex(countKey,1*60*60,"1");
                verifyCodeMsg = ESendSms.发送成功.getName();
            }else if(Integer.parseInt(count) <= 2){
                //发送次数+1
                jedis.incr(countKey);
                verifyCodeMsg = ESendSms.发送成功.getName();
            }else if (Integer.parseInt(count) > 2){
                //发送三次，不能再发送
                RedisUtil.releaseRedis(jedis);
                verifyCodeMsg =  ESendSms.一小时只可发送三条.getName();
            }

            String code = SendSmsUtil.getSendSms(phone);
            System.out.println(code);
            jedis.setex(codeKey,300,code);

        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            RedisUtil.releaseRedis(jedis);
        }
        return verifyCodeMsg;

    }

    /**
     * 校验验证码 checkVerifyCode
     * @param userPhone 手机号
     * @param code 验证码
     * @return
     */
    public static String checkVerifyCode(String userPhone, String code) {
        Jedis jedis = RedisUtil.getRedis("192.168.10.2");
        code = String.valueOf(new Code(code));
        try {
            //验证码key
            String codeKey = "PhoneNumbers:"+userPhone+",code:";
            String redisCode = jedis.get(codeKey);
            //判断
            if (redisCode.equals(code)){
                return ESendSms.验证码正确.getName();
            }else {
                return ESendSms.验证码错误.getName();
            }
        } catch (Exception e) {
            return ESendSms.验证码错误.getName();
        } finally {
            RedisUtil.releaseRedis(jedis);
        }

    }

}
